document.addEventListener('DOMContentLoaded', function() {
        new Vue({
            el: '#app',
            data: {
                taxonomyCode:'',
                taxonomy_name: '',
                // 广告计划信息
                editingBatchIndex: -1, // 当前编辑的行索引
                selectedPackageDetails:false,
                showCopyButton: false, // 控制复制按钮显示
                accountId: '111',
                productName: '',
                brandClient: '',
                pathName: '信息流-点1',
                pathOptions: [
                    "信息流-点1", "信息流-点2", "信息流-点3", "信息流-点4",
                    "信息流-点5", "信息流-点6", "信息流-互1", "信息流-站1",
                    "信息流-种1", "信息流-种2", "信息流-深1", "信息流-深2"
                ],
                recomSpu:'',
                recomSpuOptions: [],
                pathTooltips: [
                    "信息流-点1: 产品种草 - 信息流推广 - 笔记 - 点击量 - 不启用 - / - / - 稳定成本 - 不开启 - 不加入",
                    "信息流-点2: 产品种草 - 信息流推广 - 笔记 - 点击量 - 启用 - 互动量 - / - 稳定成本 - 不开启 - 不加入",
                    "信息流-点3: 产品种草 - 信息流推广 - 笔记 - 点击量 - 启用 - 站外转化量 - 淘联-小红星 - 稳定成本 - 不开启 - 不加入",
                    "信息流-点4: 产品种草 - 信息流推广 - 笔记 - 点击量 - 不启用 - / - / - 手动出价 - 不开启 - 不加入",
                    "信息流-点5: 产品种草 - 信息流推广 - 笔记 - 点击量 - 启用 - 互动量 - / - 手动出价 - 不开启 - 不加入",
                    "信息流-点6: 产品种草 - 信息流推广 - 笔记 - 点击量 - 启用 - 站外转化量 - 淘联-小红星 - 手动出价 - 不开启 - 不加入",
                    "信息流-互1: 产品种草 - 信息流推广 - 笔记 - 互动量 - / - / - / - 稳定成本 - 不开启 - 不加入",
                    "信息流-站1: 产品种草 - 信息流推广 - 笔记 - 站外转化量 - / - / - 淘联-小红星 - 最大转化 - 不开启 - 不加入",
                    "信息流-种1: 产品种草 - 信息流推广 - 笔记 - 种草人群规模 - / - / - / - 稳定成本 - 不开启 - 不加入",
                    "信息流-种2: 产品种草 - 信息流推广 - 笔记 - 种草人群规模 - / - / - / - 最大转化 - 不开启 - 不加入",
                    "信息流-深1: 产品种草 - 信息流推广 - 笔记 - 深度种草人群规模 - / - / - / - 稳定成本 - 不开启 - 不加入",
                    "信息流-深2: 产品种草 - 信息流推广 - 笔记 - 深度种草人群规模 - / - / - / - 最大转化 - 不开启 - 不加入"
                ],
                smartExpand: "关闭",
                planBudget: 100,
                consumeRate: '匀速消耗',
                unitId: '',

                // 定向设置 - 关联定向包
                targetPackages: [
                    "美妆人群包", "时尚达人包", "母婴兴趣包",
                    "科技爱好者", "美食达人包", "旅游爱好者",
                    "健康生活包", "学生党人群", "高端消费群"
                ],
                all_target_config_temp: [],
                selectedTargetPackages: [],
                selectedTempTargetPackages: [],

                // 投放时段设置
                weekDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                timeRanges: Array(7).fill().map(() => ({ start: 8, end: 23 })),

                // 更多定向
                gender: '不限',
                genderOptions: ["不限", "男", "女"],
                area: '中国',
                areaOptions: ["不限", "中国", "中国(排除港澳台)"],
                ageOptions: ["不限", "18-22", "23-27", "28-32", "33-40", "41-50", ">50"],
                ageVars: [true, false, false, false, false, false, false],
                ageAll: true,
                platform: '不限',
                platformOptions: ["不限", "android", "ios"],
                telPriceOptions: [
                    "不限", "1999元以下", "2000-3999元",
                    "4000-5999元", "6000-7999元", "8000元+"
                ],
                telPriceVars: [true, false, false, false, false, false],
                priceAll: true,
                targetCost: 0.6,

                // 创意信息
                creativeName: '',
                monitorText: '',
                exposureText: '',
                indusQualifyText: '',
                coverAll: '是',
                autoOptimize: '关闭',
                transCompType: '无',
                // transCompOptions: ["无", "落地页组件", "私信组件", "门店组件", "搜索组件"],
                transCompOptions: ["无", "搜索组件"],
                bottomVar: false,
                bottomEntry: '搜索词',
                commentVar: false,
                commentEntry: '默认评论文案',

                // 批量数据存储
                batchData: [],
                packageDetailsList: [],
                outTargetConfigs: []
            },
            mounted() {
                // 初始化定向包选择
                this.loadAccountIdAndSpu();
                this.loadTargetPackages();
                this.loadTempTargetPackages();
            },
            watch: {
                selectedTargetPackages: {
                    handler: 'handlePackageSelectionChange',
                    deep: true
                },
                selectedTempTargetPackages: {
                    handler: function(newVal) {
                        this.handleTempPackageSelectionChange();
                        // 更新复制按钮显示状态
                        this.showCopyButton = newVal && newVal.length > 0;
                    },
                    deep: true
                }
            },
            methods: {
                showPackageDetails(pkg_id, pkg_name) {
                    // 检查是否已存在相同ID的详情
                    const exists = this.packageDetailsList.some(item => item.id === pkg_id);
                    if (exists) return;

                    fetch(`http://localhost:5000/api/target_packages_details?pkg_id=${pkg_id}`)
                        .then(response => {
                            if (!response.ok) throw new Error('Network response was not ok');
                            return response.json();
                        })
                        .then(data => {
                            const outTargetConfig = data['outTargetConfig']
                            this.outTargetConfigs.push(outTargetConfig); 

                            console.log('this.outTargetConfigs:::', this.outTargetConfigs);
                            console.log('this.taxonomyCode:::', this.taxonomyCode);

                            const desc = outTargetConfig['desc']
                            data = outTargetConfig['targetConfig']
                            // 确保数据格式正确
                            const enhancedData = {
                                id: pkg_id,
                                name: pkg_name || '未知定向包',
                                desc: desc || '默认定向包描述',
                                targetGender: data.targetGender || '0',
                                targetAge: data.targetAge || '18-22#23-27#28-32#33-40#41-50',
                                targetCity: data.targetCity || '中国',
                                targetDevice: data.targetDevice || 'all',
                                targetDevicePrice: data.targetDevicePrice || 'all',
                                intelligentExpansion: data.intelligentExpansion || 0,
                                keywords: data.keywords || [],
                                interestKeywords: data.interestKeywords || [],
                                crowdPkg: (data.crowdTarget && data.crowdTarget.crowdPkg) || [],
                                industryInterestTarget: data.industryInterestTarget || {
                                    contentInterests: [],
                                    shoppingInterests: []
                                },
                                showKeywords: false,
                                showCrowdPkg: false
                            };
                            this.packageDetailsList.unshift(enhancedData);
                        })
                        .catch(error => {
                            console.error('Error fetching package details:', error);
                            // 添加默认信息
                            this.packageDetailsList.unshift({
                                id: pkg_id,
                                name: '默认定向包',
                                targetGender: '0',
                                targetAge: '18-22#23-27#28-32#33-40#41-50',
                                targetCity: '中国',
                                targetDevice: 'all',
                                targetDevicePrice: 'all',
                                intelligentExpansion: 0,
                                keywords: ['默认关键词'],
                                crowdPkg: [{
                                    name: '默认人群包',
                                    groupId: 'default'
                                }],
                                industryInterestTarget: {
                                    contentInterests: [],
                                    shoppingInterests: []
                                },
                                showKeywords: false,
                                showCrowdPkg: false
                            });
                        });
                },
                 showTempPackageDetailsByID(pkg_id, pkg_name) {
                    const exists = this.packageDetailsList.some(item => item.id === pkg_id);
                    if (exists) return;

                    // 更新复制按钮显示状态
                    this.showCopyButton = this.selectedTempTargetPackages.includes(pkg_name);

                    fetch(`http://localhost:5000/api/temp_target_packages_details_byid?pkg_id=${pkg_id}`)
                        .then(response => {
                            if (!response.ok) throw new Error('Network response was not ok');
                            return response.json();
                        })
                        .then(data => {

                            const target_config = data['target_config']
                            const desc = target_config['desc']
                            data = target_config['targetConfig']

                            const enhancedData = {
                                id: pkg_id,
                                name: pkg_name || '未知定向包',
                                desc: desc || '默认定向包描述',
                                targetGender: data.targetGender || '0',
                                targetAge: data.targetAge || '18-22#23-27#28-32#33-40#41-50',
                                targetCity: data.targetCity || '中国',
                                targetDevice: data.targetDevice || 'all',
                                targetDevicePrice: data.targetDevicePrice || 'all',
                                intelligentExpansion: data.intelligentExpansion || 0,
                                keywords: data.keywords || [],
                                interestKeywords: data.interestKeywords || [],
                                crowdPkg: (data.crowdTarget && data.crowdTarget.crowdPkg) || [],
                                industryInterestTarget: data.industryInterestTarget || {
                                    contentInterests: [],
                                    shoppingInterests: []
                                },
                                showKeywords: false,
                                showCrowdPkg: false
                            };
                            this.packageDetailsList.unshift(enhancedData);
                            
                        })
                        .catch(error => {
                            console.error('Error fetching package details:', error);
                        });
                },

                handleSpuChange(event){
                    const selectedSpuName = event.target.value; // 获取选中的 spuName
                    const selectedOption = this.recomSpuOptions.find(
                        option => option.spuName === selectedSpuName
                    );
                    if (selectedOption) {
                        const taxonomyCode = selectedOption.taxonomyCode;
                        this.taxonomyCode = taxonomyCode
                        console.log("选中的 taxonomyCode:", this.taxonomyCode);
                        this.get_indus_category_tree(this.taxonomyCode);
                        this.loadTempTargetPackages()
                    }
                },
                async get_indus_category_tree(taxonomyCode){
                    try {
                        const response = await fetch(`http://localhost:5000/api/get_indus_category_tree?taxonomy_code=${taxonomyCode}`);
                        if (!response.ok) throw new Error(`HTTP ${response.status}`);

                        const data = await response.json();
                        this.taxonomy_name = data.taxonomy_name || [];
                        console.log("taxonomy_name:::", this.taxonomy_name)

                    } catch (error) {
                        console.error('加载失败:', error);
                        this.taxonomy_name = "默认行业类目"
                    }
                },

                async loadTempTargetPackages() {  // 必须添加 async
                    try {
                        const taxonomy_code = this.taxonomyCode;

                        // 1. 尝试从Flask获取
                        const response = await fetch(`http://localhost:5000/api/get_monitor_target_config_detail?taxonomy_code=${taxonomy_code}`);
                        if (!response.ok) throw new Error(`HTTP ${response.status}`);

                        const data = await response.json();
                        this.all_target_config_temp = data.all_target_config_temp || [];

                    } catch (error) {
                        console.error('加载失败:', error);
                        this.all_target_config_temp = [{'id':204445,'target_config_temp_name':'默认人群包1'}, {'id':204446,'target_config_temp_name':'默认人群包2'}];
                    }
                },

                async loadAccountIdAndSpu() {  // 必须添加 async
                    try {
                        // 1. 尝试从Flask获取
                        const response = await fetch('http://localhost:5000/api/target_packages');
                        if (!response.ok) throw new Error(`HTTP ${response.status}`);

                        const data = await response.json();
                        this.accountId = data.account_id || '';
                        this.recomSpuOptions = data.spu_name_list || [];

                    } catch (error) {
                        console.error('加载失败:', error);
                    }
                },

                async loadTargetPackages() {  // 必须添加 async
                    try {
                        // 1. 尝试从Flask获取
                        const response = await fetch('http://localhost:5000/api/target_packages_all');
                        if (!response.ok) throw new Error(`HTTP ${response.status}`);

                        const data = await response.json();
                        this.targetPackages = data.targetPackages || [];

                        // 2. 初始化选中项
                        if (this.targetPackages.length > 0 && !this.selectedTargetPackages.length) {
                            this.selectedTargetPackages = [this.targetPackages[0]];
                        }

                    } catch (error) {
                        console.error('加载失败:', error);
                        this.targetPackages = [{'id':204445,'name':'默认人群包1'}, {'id':204446,'name':'默认人群包2'}];
                    }
                },


                deleteBatchItem(index) {
                    this.batchData.splice(index, 1);
                },

                saveBatchEdit(index) {
                    const batch = this.batchData[index];
                    batch.editing = false;

                    // 同步更新关联数据
                    batch.creativeData['笔记ID'][0] = batch.planData['笔记ID'][0];

                    // 更新转化组件相关字段
                    if (batch.creativeData['转化组件'][0] === '搜索组件') {
                        batch.creativeData['组件位置'][0] =
                            (this.bottomVar && this.commentVar ?
                            `图片或视频底部\n置顶评论` :
                            this.bottomVar ? `图片或视频底部` :
                            this.commentVar ? `置顶评论` : '');
                    } else {
                        batch.creativeData['组件位置'][0] = '';
                    }

                    // 重新生成计划名以保持一致性
                    const newPlanName = this.generatePlanName(batch.packageName);
                    batch.planData['计划名'][0] = newPlanName;
                    batch.planData['单元名称'][0] = newPlanName;

                    // 显示保存成功提示
                    const successToastEl = document.getElementById('successToast');
                    const successToast = bootstrap.Toast.getOrCreateInstance(successToastEl);
                    document.getElementById('successToastMessage').textContent = '计划修改已保存';
                    successToast.show();
                },

                // 更新生成计划名方法
                generatePlanName(pkg) {
                    const today = new Date();
                    const formattedDate = `${(today.getMonth() + 1).toString().padStart(2, '0')}.${today.getDate().toString().padStart(2, '0')}`;
                    return `${formattedDate}-${this.productName || '产品'}-${this.creativeName || '创意'}-${pkg}-${this.pathName || '路径'}`;
                },

                toggleAgeAll() {
                    if (this.ageAll) {
                        // 如果选中"不限"，取消其他选项
                        for (let i = 1; i < this.ageVars.length; i++) {
                            this.ageVars[i] = false;
                        }
                    }
                },
                uncheckAgeAll() {
                    // 如果选择了具体年龄选项，取消"不限"
                    const hasSpecificSelection = this.ageVars.slice(1).some(v => v);
                    if (hasSpecificSelection) {
                        this.ageAll = false;
                        this.ageVars[0] = false;
                    } else {
                        // 如果没有选择任何具体选项，自动选择"不限"
                        this.ageAll = true;
                        this.ageVars[0] = true;
                    }
                },
                togglePriceAll() {
                    if (this.priceAll) {
                        // 如果选中"不限"，则取消其他选项
                        for (let i = 1; i < this.telPriceVars.length; i++) {
                            this.telPriceVars[i] = false;
                        }
                    }
                },
                uncheckPriceAll() {
                    // 如果选择了具体价格选项，则取消"不限"
                    const hasSpecificSelection = this.telPriceVars.slice(1).some(v => v);
                    if (hasSpecificSelection) {
                        this.priceAll = false;
                        this.telPriceVars[0] = false;
                    } else {
                        // 如果没有选择任何具体选项，则自动选择"不限"
                        this.priceAll = true;
                        this.telPriceVars[0] = true;
                    }
                },
                updateTransComp() {
                    if (this.transCompType === '搜索组件') {
                        this.bottomVar = true;
                        this.commentVar = true;
                    } else {
                        this.bottomVar = false;
                        this.commentVar = false;
                    }
                },
                generatePlanName(pkg) {
                    const today = new Date();
                    const formattedDate = `${(today.getMonth() + 1).toString().padStart(2, '0')}.${today.getDate().toString().padStart(2, '0')}`;
                    return `${formattedDate}-${this.productName}-${this.creativeName}-${pkg}-${this.pathName}`;
                },
                getSelectedAges() {
                    if (this.ageAll) {
                        return '不限';
                    }
                    const selected = this.ageOptions.filter((_, index) => this.ageVars[index]);
                    return selected.length > 0 ? selected.join('\n') : '不限';
                },
                getSelectedTelPrices() {
                    if (this.priceAll) {
                        return '不限';
                    }
                    const selected = this.telPriceOptions.filter((_, index) => this.telPriceVars[index]);
                    return selected.length > 0 ? selected.join('\n') : '不限';
                },
                validateInputs() {
                    const errors = [];
                    if (!this.accountId.trim()) {
                        errors.push('账号ID不能为空');
                    }

                    if (!this.pathName.trim()) {
                        errors.push('路径名称不能为空');
                    }

                    if (!this.recomSpu.trim()) {
                        errors.push('推广SPU不能为空');
                    }

                    if (!this.selectedTargetPackages || this.selectedTargetPackages.length === 0) {
                        errors.push('关联定向包不能为空');
                    }

                    if (!this.planBudget || this.planBudget <= 0) {
                        errors.push('预算必须大于0');
                    }

                    if (!this.unitId.trim()) {
                        errors.push('笔记ID不能为空');
                    }

                    if (!this.creativeName.trim()) {
                        errors.push('创意名称不能为空');
                    }

                    return errors;
                },
                prepareExcelData() {
                    // 如果没有选择定向包，则使用默认值
                    const packages = this.selectedTargetPackages.length > 0 ? this.selectedTargetPackages : ['默认定向'];

                    console.log('packages', packages);


                    // 准备计划列表数据
                    const batchData = {
                        '账号ID': [],
                        '产品名称': [],
                        '品牌客户': [],
                        '计划名': [],
                        '路径名称': [],
                        '智能扩量': [],
                        '指定预算': [],
                        '推广SPU': [],
                        '消耗速率': [],
                        '单元名称': [],
                        '笔记ID': [],
                        '关联定向包': [],
                        '性别': [],
                        '地域': [],
                        '年龄': [],
                        '平台': [],
                        '手机价格': [],
                        '目标成本': [],
                        '投放时段': []
                    };

                    // 为每个定向包创建一个计划
                    packages.filter(pkg => pkg && typeof pkg === 'string' && pkg.trim()).forEach(pkg => {
                        batchData['账号ID'].push(this.accountId);
                        batchData['产品名称'].push(this.productName);
                        batchData['品牌客户'].push(this.brandClient);
                        batchData['计划名'].push(this.generatePlanName(pkg));
                        batchData['路径名称'].push(this.pathName);
                        batchData['智能扩量'].push(this.smartExpand);
                        batchData['指定预算'].push(this.planBudget);
                        batchData['推广SPU'].push(this.recomSpu);
                        batchData['消耗速率'].push(this.consumeRate);
                        batchData['单元名称'].push(this.generatePlanName(pkg));
                        batchData['笔记ID'].push(this.unitId);
                        batchData['关联定向包'].push(pkg);
                        batchData['性别'].push(this.gender);
                        batchData['地域'].push(this.area === '中国(排除港澳台)' ? '中国:not香港-澳门-台湾' : this.area);
                        batchData['年龄'].push(this.getSelectedAges());
                        batchData['平台'].push(this.platform);
                        batchData['手机价格'].push(this.getSelectedTelPrices());
                        batchData['目标成本'].push(this.targetCost);
                        batchData['投放时段'].push(this.formatTimeRanges());
                    });

                    // 准备创意信息数据
                    const creativeData = {
                        '笔记ID': [this.unitId],
                        '创意名称': [this.creativeName],
                        '监测链接': [this.monitorText],
                        '曝光链接': [this.exposureText],
                        '行业资质': [this.indusQualifyText],
                        '封面全选': [this.coverAll],
                        '自动优化': [this.autoOptimize],
                        '转化组件': [this.transCompType],
                        '组件位置': [this.transCompType === '搜索组件' ?
                                                (this.bottomVar && this.commentVar ?
                                                `图片或视频底部\n置顶评论` :
                                                this.bottomVar ? `图片或视频底部` :
                                                this.commentVar ? `置顶评论` : '') : ''],
                        '置顶评论文案': [this.transCompType === '搜索组件' ? this.commentEntry : ''],
                        '搜索词': [this.transCompType === '搜索组件' ? this.bottomEntry : ''],
                    };

                    return {
                        planData: batchData,
                        creativeData: creativeData
                    };
                },
                formatTimeRanges() {
                    return this.weekDays.map((day, index) => {
                        return `${day}:${this.timeRanges[index].start}-${this.timeRanges[index].end}`;
                    }).join('\n');
                },
                addToBatch(type) {
                    const errors = this.validateInputs();
                    if (errors.length > 0) {
                        const errorToastEl = document.getElementById('errorToast');
                        const errorToast = bootstrap.Toast.getOrCreateInstance(errorToastEl);
                        document.getElementById('errorToastMessage').innerHTML = errors.join('<br>');
                        errorToast.show();
                        return;
                    }

                    // 确保选中的定向包是唯一的
                    const uniquePackages = [...new Set(this.selectedTargetPackages)];

                    // 为每个选中的定向包创建独立计划
                    const packages = uniquePackages.length > 0
                        ? uniquePackages
                        : ['默认定向'];

                    // 先清空当前批处理数据（如果是新添加）
                    if (type === 0) {
                        this.batchData = [];
                    }

                    packages.filter(pkg => pkg && typeof pkg === 'string' && pkg.trim()).forEach(pkg => {
                        const excelData = this.prepareExcelData(pkg);
                        excelData.editing = false;
                        excelData.packageName = pkg;
                        this.batchData.push(excelData);
                    });

                    // 清空笔记ID，保留其他设置
                    this.unitId = '';

                    if (type === 1) {
                        const successToastEl = document.getElementById('successToast');
                        const successToast = bootstrap.Toast.getOrCreateInstance(successToastEl);
                        document.getElementById('successToastMessage').textContent =
                            `已添加 ${packages.length-1} 条计划到批量列表`;
                        successToast.show();
                    }
                },

                // 修改prepareExcelData方法以接受定向包参数
                prepareExcelData(packageName) {
                    // 准备计划列表数据
                    const batchData = {
                        '账号ID': [this.accountId],
                        '产品名称': [this.productName],
                        '品牌客户': [this.brandClient],
                        '计划名': [this.generatePlanName(packageName)],
                        '路径名称': [this.pathName],
                        '智能扩量': [this.smartExpand],
                        '指定预算': [this.planBudget],
                        '推广SPU': [this.recomSpu],
                        '消耗速率': [this.consumeRate],
                        '单元名称': [this.generatePlanName(packageName)],
                        '笔记ID': [this.unitId],
                        '关联定向包': [packageName],
                        '性别': [this.gender],
                        '地域': [this.area === '中国(排除港澳台)' ? '中国:not香港-澳门-台湾' : this.area],
                        '年龄': [this.getSelectedAges()],
                        '平台': [this.platform],
                        '手机价格': [this.getSelectedTelPrices()],
                        '目标成本': [this.targetCost],
                        '投放时段': [this.formatTimeRanges()]
                    };

                    // 准备创意信息数据
                    const creativeData = {
                        '笔记ID': [this.unitId],
                        '创意名称': [this.creativeName],
                        '监测链接': [this.monitorText],
                        '曝光链接': [this.exposureText],
                        '行业资质': [this.indusQualifyText],
                        '封面全选': [this.coverAll],
                        '自动优化': [this.autoOptimize],
                        '转化组件': [this.transCompType],
                        '组件位置': [this.transCompType === '搜索组件' ?
                            (this.bottomVar && this.commentVar ?
                            `图片或视频底部\n置顶评论` :
                            this.bottomVar ? `图片或视频底部` :
                            this.commentVar ? `置顶评论` : '') : ''],
                        '置顶评论文案': [this.transCompType === '搜索组件' ? this.commentEntry : ''],
                        '搜索词': [this.transCompType === '搜索组件' ? this.bottomEntry : '']
                    };

                    return {
                        planData: batchData,
                        creativeData: creativeData,
                        packageName: packageName
                    };
                },
                async generateExcel() {
                    if (this.batchData.length === 0) {
                        const errors = this.validateInputs();
                        if (errors.length > 0) {
                            alert('请解决以下错误：\n' + errors.join('\n'));
                            return;
                        }
                        this.addToBatch(0);
                    }

                    // 发送定向包配置和行业代码到Flask
                    try {
                        const response = await fetch('http://localhost:5000/api/save_target_configs_spu_map', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                outTargetConfigs: this.outTargetConfigs,
                                taxonomyCode: this.taxonomyCode,
                                taxonomyName: this.taxonomy_name,
                                recomSpu: this.recomSpu
                            })
                        });
                        if (!response.ok) {
                            throw new Error('保存定向包配置失败');
                        }
                        const result = await response.json();
                        console.log('定向包配置保存成功:', result);
                    } catch (error) {
                        console.error('保存定向包配置错误:', error);
                        // 不阻断Excel生成流程，仅记录错误
                    }

                    // 准备合并数据
                    const mergedData = {
                        planData: {},
                        creativeData: {}
                    };

                    // 初始化合并数据结构
                    const initMergedData = (data) => {
                        Object.keys(data.planData).forEach(key => {
                            if (!mergedData.planData[key]) {
                                mergedData.planData[key] = [];
                            }
                        });
                        Object.keys(data.creativeData).forEach(key => {
                            if (!mergedData.creativeData[key]) {
                                mergedData.creativeData[key] = [];
                            }
                        });
                    };

                    // 处理第一条数据以初始化结构
                    if (this.batchData.length > 0) {
                        initMergedData(this.batchData[0]);
                    }

                    // 合并所有数据
                    this.batchData.forEach(data => {
                        Object.keys(data.planData).forEach(key => {
                            mergedData.planData[key].push(data.planData[key][0]);
                        });
                        Object.keys(data.creativeData).forEach(key => {
                            mergedData.creativeData[key].push(data.creativeData[key][0]);
                        });
                    });

                    // 创建工作簿
                    const wb = XLSX.utils.book_new();

                    // 添加计划列表工作表
                    const ws1 = XLSX.utils.json_to_sheet(
                        this.formatDataForSheet(mergedData.planData)
                    );
                    XLSX.utils.book_append_sheet(wb, ws1, "计划列表");

                    // 添加创意信息工作表
                    const ws2 = XLSX.utils.json_to_sheet(
                        this.formatDataForSheet(mergedData.creativeData)
                    );
                    XLSX.utils.book_append_sheet(wb, ws2, "创意信息");

                    // 生成文件名
                    const today = new Date();
                    const formattedDate = `${today.getFullYear()}${(today.getMonth() + 1).toString().padStart(2, '0')}${today.getDate().toString().padStart(2, '0')}_${today.getHours().toString().padStart(2, '0')}${today.getMinutes().toString().padStart(2, '0')}`;
                    const filename = `聚光计划_${formattedDate}.xlsx`;

                    // 下载Excel
                    XLSX.writeFile(wb, filename);

                    // 上传到服务器
                    fetch('http://localhost:5000/api/upload_file', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ filePath: filename })
                    })
                    .then(res => res.json())
                    .then(data => {
                        console.log("上传成功", data);
                        // 清空批量数据
                        this.batchData = [];
                    })
                    .catch(err => console.error("上传失败", err));

                },
                formatDataForSheet(data) {
                    // 将列式数据转换为行式数据
                    const keys = Object.keys(data);
                    const length = data[keys[0]].length;
                    const result = [];

                    for (let i = 0; i < length; i++) {
                        const row = {};
                        keys.forEach(key => {
                            row[key] = data[key][i];
                        });
                        result.push(row);
                    }

                    return result;
                },

                // 当取消选中定向包时移除对应的详情
                handlePackageSelectionChange() {
                    // 获取当前选中的定向包ID列表
                    const selectedIds = this.targetPackages
                        .filter(pkg => this.selectedTargetPackages.includes(pkg.name))
                        .map(pkg => pkg.id);

                    // 过滤packageDetailsList，只保留选中的定向包
                    this.packageDetailsList = this.packageDetailsList.filter(detail =>
                        selectedIds.includes(detail.id)
                    );
                }, 
                handleTempPackageSelectionChange() {
                    // 获取当前选中的定向包ID列表
                    const selectedIds = this.all_target_config_temp
                        .filter(pkg => this.selectedTempTargetPackages.includes(pkg.target_config_temp_name))
                        .map(pkg => pkg.id);
                    
                    console.log("selectedIds:::", selectedIds)
                    // 过滤packageDetailsList，只保留选中的定向包
                    this.packageDetailsList = this.packageDetailsList.filter(detail =>
                        selectedIds.includes(detail.id)
                    );
                },
                
                async copyTargetPackage(detail) {
                    if (!detail) {
                        this.showErrorToast('请先选择要复制的定向包');
                        return;
                    }
                    
                    // 设置loading状态
                    detail.loading = true;
                    
                    try {
                        // 获取原始数据
                        const response = await fetch(`http://localhost:5000/api/temp_target_packages_details_byid?pkg_id=${detail.id}`);
                        if (!response.ok) throw new Error('获取定向包详情失败');
                        
                        const data = await response.json();
                        const target_config = data['target_config'];

                        // 准备提交数据
                        const postData = {
                            target_config: target_config
                        };
                        
                        const copyResponse = await fetch('http://localhost:5000/api/copy_target_package', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(postData)
                        });
                        
                        const result = await copyResponse.json();

                        if (result['message']['code'] === 0) { 
                            this.showSuccessToast('定向包复制成功');
                        } else {
                            this.showErrorToast(`定向包复制失败 - ${result['message']['msg']} - ${detail.name}`);
                        }
                        
                        // 刷新定向包列表
                        this.loadTargetPackages();
                    } catch (error) {
                        console.error('复制错误:', error);
                        this.showErrorToast(error.message || '复制定向包失败');
                    } finally {
                        // 无论成功失败都取消loading状态
                        detail.loading = false;
                    }
                },
                
                showSuccessToast(message) {
                    const toastEl = document.getElementById('successToast');
                    const toast = bootstrap.Toast.getOrCreateInstance(toastEl);
                    document.getElementById('successToastMessage').textContent = message;
                    toast.show();
                },
                
                showErrorToast(message) {
                    const toastEl = document.getElementById('errorToast');
                    const toast = bootstrap.Toast.getOrCreateInstance(toastEl);
                    document.getElementById('errorToastMessage').textContent = message;
                    toast.show();
                }
            }
        });
});